# coding=utf-8
import base64
import functools
import hashlib
import time
import types
from flask import jsonify, request, redirect
from app.MySession import MySession
from dbConnection.MysqlConn import Mysql

CODE_SUCCESS = 200
CODE_ERROR = 500
CODE_LOGIN = 301
CODE_EMPTY = 400
CODE_FAIL = 401
CODE_EXIST = 402  # 手机号码已被注册
CODE_BREAK = 403  # 参数不正确
PAGE_NUM = 12

server_url = "http://gz.deyiauto.com"


# 获取IP
def get_current_ip():
    ip = request.headers.get('X-Real-Ip', request.remote_addr)
    return ip


# 转化成json格式
def to_counts_json(response, counts):
    response_json = jsonify(response)
    response_json.headers['Access-Control-Allow-Origin'] = '*'
    response_json.headers['counts'] = counts
    return response_json


# 转化成json格式
def to_json(response):
    response_json = jsonify(response)
    response_json.headers['Access-Control-Allow-Origin'] = '*'
    return response_json


# md5加密
def md5(string):
    if isinstance(string, types.StringType):
        m = hashlib.md5()
        m.update(string)
        return m.hexdigest()
    else:
        return ''


# 时间戳转换为日期（年月日时分秒）
def int_day(timestamp):
    dd = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp))
    return dd


#  时间戳转换为日期（年月日）
def int_ymd(timestamp):
    day = time.strftime('%Y-%m-%d', time.localtime(timestamp))
    return day


# 日期转换为时间戳
def day_int(day):
    dt = int(time.mktime(time.strptime(day, '%Y-%m-%d')))
    return dt


# 返回当月的第一天跟最后一天
def getMonthFirstDayAndLastDay(year=None, month=None):
    """
    :param year: 年份，默认是本年，可传int或str类型
    :param month: 月份，默认是本月，可传int或str类型
    :return: firstDay: 当月的第一天，datetime.date类型
              lastDay: 当月的最后一天，datetime.date类型
    """
    import datetime, calendar
    if year:
        year = int(year)
    else:
        year = datetime.date.today().year
    if month:
        month = int(month)
    else:
        month = datetime.date.today().month
    # 获取当月第一天的星期和当月的总天数
    firstDayWeekDay, monthRange = calendar.monthrange(year, month)
    # 获取当月的第一天
    firstDay = datetime.date(year=year, month=month, day=1)
    lastDay = datetime.date(year=year, month=month, day=monthRange)
    return firstDay, lastDay


# 后台登录验证
def admin_login(func):
    @functools.wraps(func)
    def request_session(*args, **kwargs):
        session = request.cookies.get("uid")
        if session is None or not MySession.reactive(session):
            return redirect('/admin/login.html')
        else:
            uid = MySession.get_name(session)
        return func(*args, **kwargs)

    return request_session


# 商家登陆验证
def business_verify(func):
    @functools.wraps(func)
    def request_session(*args, **kwargs):
        session = request.values.get("session_id")
        if session is None or MySession.reactive(session) is False:
            data = {}
            data['code'] = 410
            return to_json(data)
        else:
            uid = MySession.get_name(session)
        return func(uid, *args, **kwargs)

    return request_session
